<?php

namespace app\db\model;

use think\Db;
use think\Model;

class DbDatabase extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_database';
    # --------------------------------- 查询类接口 START------------------------------------
    /**
     * 获取数据库详情信息
     * @param int  $database_id 数据库ID
     * @author MSQ 2021-8-2
    **/
    public function getDetails($database_id = 0,$field = '*')
    {
        $where = [
            'id'     => $database_id,
            'status' => 1,
        ];
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $info = $this->where($where)->value($field);
        }else{
            $info = db($this->dbName)->field($field)->where($where)->find();
            if (!$info) return [];

            $template_id = model('DbTemplate')->getUseingTemplateByDid($database_id,'id');
            $userNmae = model('DbUsercare')->getDetails($info['usercare_id'],'name');

            $info['template_id']  = $template_id;
            $info['creator_name'] = $userNmae;
            $info['create_time']  = date('Y-m-d',$info['create_time']);
        }        
        return $info;
    }
    /**
     * 获取总库所有子库
     * @param int  $database_id 总库ID
     * @author MSQ 2021-8-2
    **/
    public function getChildDbByParId($database_id = 0,$field = '*')
    {
        $where = [
            'parent_id' => $database_id,
            'status'    => 1
        ];
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $list = $this->where($where)->column($field);
        }else{
            $list = db($this->dbName)->field($field)->where($where)->select();
        }
        return $list;
    }
    /**
     * 获取医务加入的所有总库
     * @param int  $usercare_id 医务ID
     * @author MSQ 2021-8-2
    **/
    public function getAllJoinParDb($usercare_id = 0)
    {
        if (!$usercare_id) return false;
        # 当前医务加入的所有数据库列表
        $databaseAll = model('DbUsercareRelation')->getJoinDatabaseByUsercareId($usercare_id);
        # 所有需要展示的总库id
        $masterDatabaseList = [];
        foreach ($databaseAll as $k => $v) {
            if (!isset($masterDatabaseList[$v['id']]) && !$v['parent_id']) {//总库
                $v['total']  = model('DbUser')->getUserAllCount($v['id']); //总库统计病例数
                $masterDatabaseList[$v['id']] = $v;
            } else {//不是总库，则找到对应的总库
                if (!isset($masterDatabaseList[$v['parent_id']])) {
                    $masterDb = $this->getDetails($v['parent_id']);
                    $masterDb['total'] = model('DbUser')->getUserAllCount($v['parent_id']); ////总库统计病例数
                    $masterDatabaseList[$v['parent_id']] = $masterDb;
                }
            }
        }
        # 重置KEY从0开始
        $masterDatabaseList = array_values($masterDatabaseList);        
        return $masterDatabaseList;
    }
    /**
     * 获取对应总库数据库及其（当前医务加入的）子库信息
     * @param int  $usercare_id 医务ID
     * @author MSQ 2021-8-2
    **/
    public function getJoinDbListByParId($usercare_id = 0,$database_id = 0)
    {
        if (!$usercare_id || !$database_id) return false;

        $databaseInfo = $this->getDetails($database_id);
        if (!$databaseInfo || $databaseInfo['parent_id']) return false;

        # 该总库所有子库id
        $childDbIds = $this->getChildDbByParId($database_id,'id');

        # 将总库id放入数组
        array_unshift($childDbIds,$database_id);
        # 检测医务加入的库
        $joinDb = model('DbUsercareRelation')->getJoinInfoByDbIds($usercare_id,$childDbIds,'database_id');
        if (!$joinDb) return [];//不能查看当前数据库
        $joinDb = array_flip($joinDb);
        # 剔除总库，即加入的所有子库
        if (isset($joinDb[$database_id])) unset($joinDb[$database_id]);
        
        $joinChildDb = [];
        if ($joinDb) {
            # 我加入的子库信息
            $where = [
                'id'     => ['IN',array_keys($joinDb)],
                'status' => 1,
            ];
            $joinChildDb = db($this->dbName)->where($where)->select();
            //子库统计病例数
            foreach ($joinChildDb as $key => $value) {
                $joinChildDb[$key]['total'] =  model('DbUser')->getUserAllCount($value['id'],$value['parent_id']);
            }
        }
        $databaseInfo['childDbInfo'] = $joinChildDb ? $joinChildDb : [];

        return $databaseInfo;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------
    
    # --------------------------------- 验证类接口 START------------------------------------

    /**
     * 验证数据-创建数据库
     * @param int  $parent_id 父级数据库
     *             $template_id 引用模板id 0表示自定义模板
     *             $database_name 数据库名称
     * @author MSQ 2021-8-2
     */
    public function checkDataForcreateDb($parent_id = 0,$template_id = 0,$database_name = '')
    {
        if (!$database_name) return (['code' => 0,'msg' => '数据库名称不能为空']);

        # 验证父级数据库
        if ($parent_id) {
            if (!$template_id) return ['code' => 0,'msg' => '子库必须要有引用模板'];

            $parentInfo = $this->getDetails($parent_id);
            if (!$parentInfo) return ['code' => 0,'msg' => '父级数据库不存在'];

            if ($parentInfo['parent_id']) return ['code' => 0,'msg' => '父级数据库非总库'];

            if ($parentInfo['database_name'] == $database_name) return ['code' => 0,'msg' => '不能与总库名称相同'];
        }
        # 验证数据库重名
        $where = [
            'parent_id'     => $parent_id,
            'database_name' => $database_name,
            'status'        => 1,
        ];
        $isSameName = $this->where($where)->value('id');
        if ($isSameName) return ['code' => 0,'msg' => '已存在相同数据库名称'];

        # 验证引用模板
        if ($template_id) {
            $templateInfo = model('DbTemplate')->getDetails($template_id);
            if (!$templateInfo) return ['code' => 0,'msg' => '模板不存在'];

            if ($templateInfo['is_use'] != 1) return ['code' => 0,'msg' => '模板状态异常'];
        }
        return ['code' => 1];
    }
    # ---------------------------------- 验证类接口 END-------------------------------------

 
    # ------------------------------- 数据处理类接口 START----------------------------------
    /**
     * 创建数据库
     * @param int  $parent_id 父级数据库
     *             $template_id 引用模板id 0表示自定义模板
     *             $database_name 数据库名称
     *             $db_introduction 数据库简介
     * @author MSQ 2021-8-2
     */
    public function createDatabase($parent_id = 0,$origin_template_id = 0,$database_name = '',$db_introduction = '',$usercare_id = 0)
    {
        $time = time();
        Db::startTrans();
        # 新增数据库
        $database_id = $this->createDatabaseData($database_name,$parent_id,$db_introduction,$usercare_id);
        if (!$database_id) {
            Db::rollback();
            return ['code' => 2,'msg' => '新增数据库失败'];
        }
        $template_id = model('DbTemplate')->createTemplate($database_id,$origin_template_id,$usercare_id);
        if (!$template_id) {
            Db::rollback();
            return ['code' => 2,'msg' => '模板引用失败'];
        }
        $joinData = [
            'database_id'   => $database_id,
            'usercare_id'   => $usercare_id,
            'relation_auth' => model('DbUsercareAuth')->get_auth('id','','string'),
            'join_time'     => $time,
        ];
        $joinDb = model('DbUsercareRelation')->addData($joinData);
        if (!$joinDb) {
            Db::rollback();
            return ['code' => 2,'msg' => '创建者加入数据库失败'];
        }
        session('_database_id',$database_id);
        Db::commit();
        $databaseInfo = $this->getDetails($database_id);

        return ['code' => 1,'msg' => '创建成功','data' => $databaseInfo];
    }
    /**
     * 创建数据库数据
     * @param int  $parent_id 父级数据库
     *             $database_name 数据库名称
     *             $db_introduction 数据库简介
     * @author MSQ 2021-8-2
     */
    public function createDatabaseData($database_name = '',$parent_id = 0,$db_introduction = '',$usercare_id = 0)
    {
        if (!$database_name) return false;

        $data = [
            'usercare_id' => $usercare_id,
            'parent_id'   => $parent_id,
            'database_name' => $database_name,
            'database_introduction' => $db_introduction
        ];
        $this->setAttr('id',null)->isUpdate(false)->save($data);
        if (!isset($this->id)) return false;
        return $this->id;
    }
    /**
     * 删除数据库
     * @param int  $database_id 数据库id
     * @author MSQ 2021-8-21
     */
    public function deleteDatabase($database_id = 0)
    {
        if (!$database_id) return false;
        
        $databaseInfo = $this->getDetails($database_id);
        if (!$databaseInfo) return false;

        # 相关数据库及模板 模板=>数据库
        $relevantData = model('DbTemplate')->getChildDbOrTemplate($database_id);
        if (!$relevantData) return false;

        $databaseInfo['relevantData'] = $relevantData;

        # 删除相关模板(含子库) 含删除目录&模块&变量&选项
        $res = model('DbTemplate')->deleteDbTemplate($databaseInfo);
        if (!$res) return false;

        # 删除数据库所有用户 含复制病例&用户&回答&模块关联回答(子库仅删除复制病例)
        $res = model('DbUser')->deleteUserLogic($databaseInfo);
        if (!$res) return false;

        # 删除医务
        $where = [
            'database_id' => ['IN',$relevantData],
            'relation_status' => 1
        ];
        $res = model('DbUsercareRelation')->saveData($where,['relation_status' => 0]);
        if (!$res) return false;

        # 清除上次访问数据库
        $res = model('DbUsercare')->clearFefaultDbShowIdForDelDb($database_id);
        if (!$res) return false;

        # 删除数据库数据
        $res = $this->deleteDatabaseData($relevantData);
        if (!$res) return false;

        return true;
    }
     /**
     * 删除数据库数据
     * @param int  $database_id 数据库id 可为数组 删除总库时同步删除子库
     * @author MSQ 2021-8-21
     */
    public function deleteDatabaseData($database_id = [])
    {
        if (!$database_id) return false;

        if (!is_array($database_id)) $database_id = [$database_id];

        $where = [
            'status' => 1,
            'id'     => ['IN',$database_id]
        ];
        $res = $this->update(['status' => 0],$where);
        if (!$res) return false;
        return true;
    }
    # --------------------------------- 数据处理类接口 END----------------------------------
}
